package logic

import (
	"book-hub/models"
	"context"
	"fmt"

	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectDeleteLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectDeleteLogic {
	return &CollectDeleteLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectDeleteLogic) CollectDelete(in *bookrpc.CollectDeleteRequest) (*bookrpc.CollectDeleteResponse, error) {
	// todo: add your logic here and delete this line
	var Collect models.Collect
	tx := models.DB.Begin()
	tx.Where("Novel_id=?", in.NovelId).Find(&Collect)
	if Collect.ID == 0 {
		tx.Callback()
		return nil, fmt.Errorf("当前小说未收藏")
	}
	tx.Delete(&Collect)
	var novel models.Novel
	tx.Where("id=?", in.NovelId).Find(&novel)
	if novel.ID != 0 {
		novel.CollectCount = novel.CollectCount - 1
	}
	tx.Updates(&novel)
	tx.Commit()
	return &bookrpc.CollectDeleteResponse{
		CollectId: int64(Collect.ID),
	}, nil
}
